package com.itany.shop.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 石小俊
 */
// 过滤器的配置一般是用于处理多个请求的
// 因此,其url-pattern一般使用通配符配置
@WebFilter(urlPatterns = "/*")
public class LogFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("*******************过滤器的初始化方法*******************");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("*******************过滤器的核心业务逻辑*******************");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String ip = request.getRemoteAddr();
        String uri = request.getRequestURI();
        System.out.println(ip + "在" + new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date()) + "访问了" + uri + "请求");
        // 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("*******************过滤器的销毁方法*******************");
    }
}
